<?php

namespace Beerus\Modules\CategoryEntrance\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\category\CategorySearchKeywords;
use Doraemon\model\Category as mCategory;
use Doraemon\service\Category as sCategory;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CategorySearchKeywordsController extends Controller
{

    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Content $content)
    {
        $list = CategorySearchKeywords::selectList(['use_state' => 1]);
        $cateIds = $list ? array_column($list, 'category_id') : [];
        $cateList = $cateIds ? mCategory::selectByWhere(['id' => $cateIds], ['id', 'cate_name', 'deep']) : [];
        $cateList = $cateList ? array_column($cateList, null, 'id') : [];
        foreach ($list as &$row) {
            $row['cate_name'] = isset($cateList[$row['category_id']]) ? $cateList[$row['category_id']]['cate_name'] : '';
            $row['deep'] = isset($cateList[$row['category_id']]) ? $cateList[$row['category_id']]['deep'] . '级分类' : '';
        }
        $gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('category_id', '分类id');
            $grid->column('cate_name', '分类名称');
            $grid->column('deep', '级别');
            $grid->column('search_keywords', '搜索词');
        });
        return $content->header('分类搜索关键词')->row($gridList);
    }

    /**
     *
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, $id = 0)
    {
        $info = [];
        if ($id) {
            $info = CategorySearchKeywords::getInfo(['id' => $id]);
        }
        $all = sCategory::getAllCategorys();
        $options = [];
        foreach ($all as $firstRow) {
            $options[$firstRow['id']] = $firstRow['cate_name'];
            if (isset($firstRow['children'])) {
                foreach ($firstRow['children'] as $secondRow) {
                    $options[$secondRow['id']] = $firstRow['cate_name'] . '<<' . $secondRow['cate_name'];
                    if (isset($secondRow['children'])) {
                        foreach ($secondRow['children'] as $thirdRow) {
                            $options[$thirdRow['id']] = $firstRow['cate_name'] . '<<' . $secondRow['cate_name'] . '<<' . $thirdRow['cate_name'];
                            if (isset($thirdRow['children'])) {
                                foreach ($thirdRow['children'] as $fourRow) {
                                    $options[$fourRow['id']] = $firstRow['cate_name'] . '<<' . $secondRow['cate_name'] . '<<' . $thirdRow['cate_name'] . '<<' . $fourRow['cate_name'];
                                }
                            }
                        }
                    }
                }
            }
        }
        $form = new Form($info);
        $form->hidden('id', 'id');
        if ($info) {
            $form->select('category_id', '分类')->options($options)->disable();
        } else {
            $form->select('category_id', '分类')->options($options)->required();
        }
        $form->textarea('search_keywords', '搜索词')->help('多个词用英文逗号隔开');
        $form->action(url('/admin/categoryEntrance/searchkeywords/save'));
        return $content->header('编辑活动')
            ->breadcrumb([
                'text' => '类目搜索词',
                'url' => '/categoryEntrance/searchkeywords'
            ], ['text' => '编辑搜索词'])
            ->row($form);
    }


    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->all();
            $id = $params['id'];
            $data = [
                'search_keywords' => trim(str_replace("，", ",", $params['search_keywords'])),
                'use_state' => 1,
            ];
            if ($id) {
                CategorySearchKeywords::updateData($data, ['id' => $id]);
            } else {
                $data['category_id'] = $params['category_id'];
                $info = CategorySearchKeywords::getInfo(['category_id' => $params['category_id']]);
                $id = $info ? $info['id'] : [];
                if ($id) {
                    CategorySearchKeywords::updateData($data, ['id' => $id]);
                } else {
                    CategorySearchKeywords::insertData($data);
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/categoryEntrance/searchkeywords')->with(compact('success'));
    }

    public function del(Request $request, $id = 0)
    {
        try {
            $info = CategorySearchKeywords::getInfo(['id' => $id]);
            if (!$info) {
                throw new \Exception('信息不存在');
            }
            CategorySearchKeywords::updateData(['use_state' => 9], ['id' => $id]);
            $success = [
                'message' => '删除成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'message' => '删除成功,信息:' . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

}
